package com.eshopkeeper.core.util.yunzhi;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * token工具类
 * @author chen
 *
 */
public class TokenUtil {

    private static final Log logger = LogFactory.getLog(TokenUtil.class);

    public static String genToken(Map<String,Object> map){
        String token = "";
        try {
            if(!map.containsKey("userId") || null == map.get("userId")){
                return token;
            }
            SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            Date sysdate = new Date();
            if(!map.containsKey("sysTime") || null == map.get("sysTime")) {
                calendar.setTime(new Date());
            } else {
                calendar.setTime((Date) map.get("sysTime"));
                sysdate = (Date) map.get("sysTime");
            }
            calendar.add(Calendar.MINUTE,Integer.valueOf(String.valueOf(map.get("validTime"))));
            Date date = dataFormat.parse(dataFormat.format(calendar.getTime()));
            logger.info("genToken的validTime="+map.get("validTime")+",date="+date);
            logger.info("secret:"+Config.TOKEN_HMAC256_KEY);
            token = JWT.create()
                    .withSubject(String.valueOf(map.get("userId")))
                    .withExpiresAt(date)
                    .withIssuedAt(sysdate)
                    .sign(Algorithm.HMAC256(Config.TOKEN_HMAC256_KEY));
        }catch (Exception e){
            logger.error("token生成失败",e);
            System.out.println(e);
        }
        return token;
    }
}
